package com.xq.utils;

import cn.hutool.core.util.StrUtil;
import org.springframework.cglib.beans.BeanMap;

import java.util.HashMap;
import java.util.Map;

/**
 * map工具类
 *
 * @author xu
 * 2021/8/4 11:01
 */
public class MapUtil {
    public static String toParamsFromMap(Map<String, String> objectMap) {
        // 当没有元素时直接返回空
        if(null == objectMap){
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        objectMap.forEach((k,v)->{
            // 当 k  v 不为空时就添加进来
            if(StrUtil.isNotBlank(k) && !StrUtil.isBlankIfStr(v)){
                stringBuilder
                        .append("&")
                        .append(k)
                        .append("=")
                        .append(v);
            }
        });
        // 去除第一个 &
        stringBuilder.delete(0,stringBuilder.indexOf("&")+1);
        return stringBuilder.toString();
    }

    public static void main(String[] args) {


        //System.out.println(toParamsFromMap(beanToMap(testEntity)));
    }

    /**
     * 将对象转换为map
     *
     * @param bean
     * @return
     */
    public static <T> Map<String, String> beanToMap(T bean) {
        Map<String, String> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                // key 空
                if(StrUtil.isBlankIfStr(key)) {
                    continue;
                }
                // value 空
                if(StrUtil.isBlankIfStr(beanMap.get(key))) {
                    continue;
                }
                map.put(key.toString(), beanMap.get(key).toString());
            }
        }
        return map;
    }





    /**
     * 将map转换为javabean对象
     *
     * @param map
     * @param bean
     * @return
     */
    public static <T> T mapToBean(Map<String, Object> map, T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    /**
     * 将对象字段以逗号隔开的方式展现出来
     * @param bean
     * @param <T>
     * @return
     */
    public static <T> String beanToString(T bean){
        StringBuilder stringBuilder = new StringBuilder();
        if(bean == null){
            return stringBuilder.toString();
        }
        BeanMap beanMap = BeanMap.create(bean);
        for (Object key : beanMap.keySet()){
            String keyStr = key.toString();
            stringBuilder
                    .append(",")
                    .append(keyStr);
        }
        // 去除第一个 ,
        stringBuilder.delete(0,stringBuilder.indexOf(",")+1);
        return stringBuilder.toString();
    }
}
